package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String id = request.getParameter("id");
        String password = request.getParameter("password");
        String rememberMe = request.getParameter("rememberMe");

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/FinalTest", "root", "123456");
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM user WHERE name = ? AND password = ?");
            ps.setString(1, id);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                HttpSession session = request.getSession();
                session.setAttribute("user", id);

                if (rememberMe != null && rememberMe.equals("true")) {
                    Cookie cookie = new Cookie("user", id);
                    cookie.setMaxAge(7 * 24 * 60 * 60); // 1周
                    response.addCookie(cookie);
                }
                response.sendRedirect("userList?page=1"); // 跳转到第一页
            } else {
                response.sendRedirect("loginFailed.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
